var rootPath = '';//kk.getRootPath();

/* userDom */
var userDom = '\
<div class="box box-skin-inner sub-content">\
	<div class="box-header with-border">\
		<span class="box-title"></span>\
		<div class="box-tools pull-right">\
			<button type="button" class="btn btn-box-tool btnCancel" data-widget="remove"><i class="fa fa-times"></i></button>\
		</div>\
	</div>\
	<div class="box-body">\
		<div class="row">\
			<form class="form-horizontal" id="userForm">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="myFile" class="col-sm-2 control-label">头像</label>\
					<div class="col-sm-10">\
						<input type="file" id="myFile" name="file" />\
						<input type="hidden" id="avatar" name="avatar" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="username" class="col-sm-2 control-label">用户名<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="username" name="username" placeholder="用户名">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="real_name" class="col-sm-2 control-label">姓名<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="real_name" name="real_name" placeholder="姓名">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="email" class="col-sm-2 control-label">邮箱<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="email" name="email" placeholder="邮箱">\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="nRoleName" class="col-sm-2 control-label">角色</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="nRoleName" name="nRoleName" placeholder="角色">\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="add_time" class="col-sm-2 control-label">添加日期</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="add_time" name="add_time" placeholder="添加日期">\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
				<div class="foo">\
					<p class="text-muted">1. 图片的尺寸为450*450</p>\
					<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
					<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
					<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
					<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
					<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
				</div>\
			</div>\
			<div class="rm-or-hide">\
				<input type="hidden" name="id" />\
			</div>\
			</form>\
		</div>\
	</div>\
	<div class="box-footer text-center">\
		<button type="button" class="btn btn-info btn-flat btnOK">确定</button>\
		<button type="button" class="btn btn-default btn-flat btnCancel">取消</button>\
	</div>\
</div>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDUserFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Admin/User/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Admin/User/delete?id=' + id;
		kk.deleteObj(url, '#table');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
		
	$('.main-content').hide();
	$('.main-content').after(userDom);
	
	var xqu = xqupload('#myFile', {
		uploadUrl			: rootPath + '/Asset/Upload/upload?savePath=user_avatar',
        recvObj				: '#avatar'
    });
	
	if (operCode == CREATE) {
		$('.box-title').empty().append('添加');

    	xupload('#myFile', {
    		height: 220,
    		changeHandler: function($this) {
    			$('#avatar').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/users/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});

		$('.rm-or-hide').remove();
	} else if (operCode == READ) {
		$('.box-title').empty().append('查看');
		$('.btnOK').hide();
		$('.btnCancel').text('关闭');

		$('#userForm').setForm(obj);
		var str = '';
		if (!obj.roleNames || obj.roleNames.length == 0) {
			str = "无";
		} else { 
			for (var i in obj.roleNames) {
				str += obj.roleNames[i] + ' ';
			}
		}
		$("input[name='nRoleName']").val(str);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.avatar,
    		isDisabled: true
    	});
    	$('#add_time').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.add_time));

		$('#userForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
	} else if (operCode == UPDATE) {
		$('.box-title').empty().append('编辑');
		
		$('#userForm').setForm(obj);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.avatar,
    		changeHandler: function($this) {
    			$('#avatar').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/users/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
    	
		$('.rm-or-hide').hide();
	}

	var validator = $("#userForm").validate({
		onfocusout: function(element) {
			$(element).valid();
		},
	    rules: {
			username: "required",
			real_name: "required",
			email: {
				required: true,
				email: true
			}
	    },
	    messages: {
			username: "请输入用户名",
			real_name: "请输入姓名",
			email: {
		    	required: "请输入Email地址",
		    	minlength: "请输入正确的email地址"
			}
	    }
	});
	
	$('.btnOK').off('click').on('click', function() {
 		if (validator.form() && doCU(operCode, id, index)) {
			$('.sub-content').remove();
			$('.main-content').show();
 		}
	});
	
	$('.btnCancel').off('click').on('click', function() {
		xqu.abort();
		
		$('.sub-content').remove();
		$('.main-content').show();
	});
}

/* Create & Update */
function doCU(operCode, id, index) {
    var url;
    var method;
	var jsonStr = JSON.stringify($('#userForm').serializeObject());
	var result;
	
	if (operCode == CREATE) {
	 	url = rootPath + '/Admin/User/save';
		method = "POST";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('insertRow', {
				index: 0,
				row: result.obj
			});
	    	
	    	return true;
		}
	} else if (operCode == UPDATE) {
		url = rootPath + '/Admin/User/update?id=' + id;
		method = "PUT";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('updateRow', {
	    		index: index,
				row: result.obj
	    	});
	    	
	    	return true;
		}
	}
	
	return false;
}


/* configure role for user */
var addRolesDom = '\
	<div class="roleOption">\
		<div class="alert alert-warning alert-dismissible fade in" role="alert">\
			<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>\
			<h4>注意!</h4>\
			<p>变更授权后，需要手动刷新表格才能看到角色变化。</p>\
			<p>变更授权后，需要用户重新登录授权才可生效。</p>\
		</div>\
	</div>\
';

function addRoles(id, index) {
	var result;
	
	xpopup.window({
	    height: 400,
		title: '授权',
	    content: addRolesDom,
        buttons: [{
        	id:	'btnOk',
            text: '确定',
            'class': 'btn btn-info btn-flat',
            handler: function ($this) {
            	// roleIdList
                var roleIdList = new Array();
				$("input[name='checkbox']:checkbox:checked").each(function() {
                	roleIdList.push(parseInt($(this).val()));
            	});
			    var jsonStr = JSON.stringify(roleIdList);
				
			    var url = rootPath + '/Admin/User/addRoles?id=' + id;
			    
				result = kk.doStrAjax(url, "PUT", jsonStr);						
			    if (result.code == 0) {
			    	$('#table').bootstrapTable('updateRow', {						// BUG: 不能刷新角色列表
			    		index: index,
			    		row: result.obj
			    	});
			    	$this.destroy();
			    }
            }
        }, {
        	id:	'btnCancel',
            text: '取消',
            'class': 'btn btn-default btn-flat',
            handler: function ($this) {
        		$this.destroy();
            }
        }],
        afterShow: function ($this) {
			var url = rootPath + '/Admin/Role/getAll';
			var roleList = kk.getObj(url);
			for (var i in roleList) {
				var roleOptionBlock = ' \
					<div class="roleOptionBlock"> \
						<label> \
					        <input type="checkbox" name="checkbox" value="' + roleList[i].id + '" />\
					        <i class="' + roleList[i].extInfo + '" /> ' + roleList[i].name + ' \
						</label> \
					</div>';
				$(".roleOption").append(roleOptionBlock);
			}
			
			var url = rootPath + '/Admin/Role/getRoleIds4User?userId=' + id;
			var roleIds = kk.getObj(url);
			for (var i in roleIds) {
				$('input[name="checkbox"]:checkbox').each(function() {
					if ($(this).val() == roleIds[i]) {
						$(this).attr('checked', true);
					}
				});
			}
        }
	});
}



/************ forbidden ************/
function forbiddenUserFunc(id, index) {
	var url = rootPath + '/Admin/User/audit?id=' + id + '&status=';
	
	xpopup.confirm({
    	title: '禁用',
        msg: '禁用？',
        buttons: [{
            text: '启用',
            'class': 'btn btn-success',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '1',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    				   		xpopup.notify({
    				           	style: 'mini',
    				           	type: 'success',
//    				           	title: '操作成功',
    		   	                msg: data.msg,
    							delay: 1000,
    							position: 'center',
    						});

    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '禁用',
            'class': 'btn btn-danger',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '-2',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    	    		   		xpopup.notify({
    	    		           	style: 'mini',
    	    		           	type: 'success',
//    	    		           	title: '操作成功',
    	                        msg: '已禁用',
    	    					delay: 1000,
    	    					position: 'center',
    	    				});
    	    		   		
    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '取消',
            'class': 'btn btn-default',
            handler: function ($this) {
        		$this.destroy();
            }
        }]
    });
}